/**
 * @file: vscode
 * @author: v_xieyejiang
 * @Date: 2018-12-10 11:31:20
 * @Last Modified by: v_xieyejiang
 * @Last Modified time: 2018-12-10 14:42:50
 */

import axios from 'axios';
import getEnv from './getEnv';
import cookie from '@/utils/cookie';
import {fmtURL} from '@/utils';
import {Message} from 'element-ui';

// 创建axios实例
const instance = axios.create({
    baseURL: getEnv,
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json'
    },
    withCredentials: true
});

// // request过滤器
instance.interceptors.request.use(
    config => {
        config.headers.authorigin = `${window.location.origin}/login`;
        config.headers.ticket = fmtURL('ticket', window.location.href);
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// // response过滤器
instance.interceptors.response.use(
    res => {
        // 未登录
        if (res.data.code === 401 || res.data.code === 302) {
            cookie.setCookie('lasthref', window.location.href);
            location.href = res.data.data.callback;
            return res;
        }
        if (res.data.code !== 200) {
            Message.error(`提示！${res.data.message}`);
        }
        return res;
    },
    err => {
        Message.error(`错误：${err.message}`);
        return Promise.reject(err);
    }
);

// 返回axios实例
export default instance;
